/* CsJni - .NET / Java Bridge
 * 
 * Copyright 2010 Robert E. Burke Licensed under the Apache License, Version 
 * 2.0 (the "License"); you may not use this file except in compliance with 
 * the License. You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 
 * law or agreed to in writing, software distributed under the License is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License. 
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;

namespace CsJni
{
    public sealed partial class JniEnvironment
    {
        #region Private Data

        private static JniNativeInterface mFunctions; // TODO - review statics

        private bool mIsMain;
        private IntPtr mHandle;
        private int mUnmanagedThreadAffinity;
        private Stack<JniLocalFrame> mFrameStack = new Stack<JniLocalFrame>();

        #endregion Private Data

        #region Internal Methods

        internal JniEnvironment(bool isMain, 
            IntPtr environmentHandle, int threadAffinity)
        {
            mIsMain = isMain;
            mHandle = environmentHandle;
            mUnmanagedThreadAffinity = threadAffinity;
            if (mIsMain)
            {
                if (mFunctions != null)
                {
                    throw new InvalidOperationException(JniResourceManager.Instance.GetString("jniOnlyOneDefaultJniEnv"));
                }
                mFunctions = new JniNativeInterface(mHandle, JavaVM.JniVersion);
            }
        }

        ~JniEnvironment()
        {
            JavaVM.HandleEnvironmentFinalization(this);
        }

        internal static void Release()
        {
            mFunctions = null;
        }

#if (DEBUG)
        internal void CheckThreadAffinity()
        {
            // Sanity check that this JniEnvironment is not being used across threads
            if (!JniEnvironmentCache.CheckThreadAffinity(this))
            {
                throw new JniException("TODO");
            }
        }
#endif // DEBUG

        internal void PushFrame(JniLocalFrame frame)
        {
#if (DEBUG)
            CheckThreadAffinity();
#endif // DEBUG
            mFrameStack.Push(frame);
        }

        internal void PopFrame(JniLocalFrame frame)
        {
#if (DEBUG)
            CheckThreadAffinity();
#endif // DEBUG
            // NOTE: check for imbalanced frames.  Frames should 
            // always be popped using the SafePop method in a finally block.
            if (0 == mFrameStack.Count)
            {
                throw new JniException("TODO");
            }
            JniLocalFrame popped = mFrameStack.Pop();
            if (!Object.ReferenceEquals(frame, popped))
            {
                throw new JniException("TODO");
            }
        }

        internal void AddToCurrentFrame(JniObject jniObject)
        {
#if (DEBUG)
            CheckThreadAffinity();
#endif // DEBUG
            if (mFrameStack.Count > 0)
            {
                mFrameStack.Peek().Add(jniObject);
            }
            else
            {
                // NOTE: All local Java references MUST be added to a frame, see JniLocalFrame for details.
                throw new JniException("TODO");
            }
        }

        internal void RemoveFromCurrentFrame(JniObject jniObject)
        {
#if (DEBUG)
            CheckThreadAffinity();
#endif // DEBUG
            if (mFrameStack.Count > 0)
            {
                mFrameStack.Peek().Remove(jniObject);
            }
            else
            {
                // NOTE: All local Java references MUST be added to a frame, see JniLocalFrame for details.
                throw new JniException("TODO");
            }
        }

        #endregion Internal Methods

        #region Private Helper Methods

        internal static JniNativeInterface Functions
        {
            get { return mFunctions; }
        }

        #endregion Private Helper Methods

        #region Public Methods

        public int ThreadAffinity
        {
            get { return mUnmanagedThreadAffinity; }
        }

        public IntPtr Handle
        {
            get { return mHandle; }
        }

        public JniLocalFrame CreateLocalFrame(int capacity)
        {
            return new JniLocalFrame(this, capacity);
        }

        public JniThreadMonitor CreateThreadMonitor(JniObject objectHandle)
        {
            return new JniThreadMonitor(this, objectHandle);
        }

        #endregion Public Methods

        #region JNI Wrapper Methods

        public JniVersion Version // GetVersion
        {
            get
            {
                int result = JniEnvironment.Functions.GetVersion(this.Handle);
                JniThrowable.CheckException(this);
                if (!Enum.IsDefined(typeof(JniVersion), result))
                {
                    string message = JniResourceManager.Instance.GetString("jniInvalidReturnedVersion") +
                        result.ToString(CultureInfo.InvariantCulture);
                    throw new JniException(message);
                }
                return (JniVersion)result;
            }
        }

        public IntPtr JavaVMHandle // GetJavaVM
        {
            get
            {
                unsafe
                {
                    void** ppVM = null;
                    int result = JniEnvironment.Functions.GetJavaVM(this.Handle, &ppVM);
                    if (0 != result)
                    {
                        JniException.CheckErrorCode(this, result);
                    }
                    // EXCEPTION CHECK: Do nothing, already checked for exception above.
                    return new IntPtr((void*)ppVM);
                }
            }
        }

        // The remainder of JNI Methods are for JNI_VERSION_1_4 or higher, 
        // corresponding delegates will be null

        #endregion JNI Wrapper Methods 
    }
}
